<template>
	<view>
		<uni-nav-bar leftIcon="arrow-left" rightText="搜索" leftWidth="40rpx" rightWidth="60rpx" fixed="true"
			@clickLeft="back" @clickRight="search(this.keywords)" statusBar>
			<uni-search-bar radius="100" v-model="keywords" clearButton="none" cancelButton="none" @focus="focus"
				@input="input" @confirm="search(this.keywords)" />
		</uni-nav-bar>
		<uni-title type="h2" title="单曲" style="margin-left: 20rpx;"></uni-title>
		<view class="single-content">
			<uni-list>
				<uni-list-item v-for="(item,i) in songs" :key="i" :title="item.name" :note="artists[i]" clickable
					@click="goSong(item.id,i)">
				</uni-list-item>
			</uni-list>
		</view>
		<player v-if="detail"></player>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex' //引入mapState
	export default {
		data() {
			return {
				keywords: '',
				songs: [],
				artists: []
			}
		},
		computed: mapState([
			'url',
			'detail'
		]),
		methods: {
			...mapMutations(['setSongId', 'setAudioSrc', 'play', 'setDetail', 'setMusicList']),
			...mapActions(['getAudioSrc']),
			back() {
				uni.navigateTo({
					url: '../search/search',
				});
			},
			focus() {
				if (!this.keywords) {
					this.back()
				}
			},
			input(res) {
				// console.log(res)
				if (!res) {
					this.back()
				}
			},
			// 搜索结果
			search(keywords) {
				uni
					.request({
						url: this.url + `/cloudsearch?keywords=${keywords}`
					})
					.then((res) => {
						// console.log(res.data);
						this.songs = res.data.result.songs
						for (let item of this.songs) {
							let artistName = ''
							for (let a of item.ar) {
								artistName += a.name + '/'
							}
							artistName = artistName.substring(0, artistName.length - 1)
							this.artists.push(artistName)
						}
					})
					.catch((err) => {
						console.error(err);
					});
			},
			// 选择歌曲
			goSong(songId, i) {
				// console.log(this.songs[i]);
				this.setMusicList(this.songs[i])
				this.setDetail(this.songs[i])
				// this.setSongId(songId)
				this.getAudioSrc(songId)
			}

		},
		onLoad(option) {
			if (!option.keywords) {
				this.back()
			}
			this.keywords = option.keywords
			this.search(this.keywords)
		}
	}
</script>

<style lang="scss">
	.uni-searchbar {
		width: 100%;
		padding: 0;
		align-items: center;
	}

	.single-content {
		padding-bottom: 100rpx;
	}
</style>
